package leetcode;

import java.util.LinkedList;

public class Lc394 {


    public String decodeString(String s) {

        StringBuilder builder = new StringBuilder();
        LinkedList<Integer> numq = new LinkedList<>();
        LinkedList<String> strq = new LinkedList<>();
        for (int i = 0; i < s.length(); ) {
            if (Character.isDigit(s.charAt(i))) {
                int idx = i;
                while (idx < s.length() && Character.isDigit(s.charAt(idx))) {
                    idx++;
                }
                numq.push(Integer.valueOf(s.substring(i, idx)));
                i = idx;
            } else if (Character.isLetter(s.charAt(i))) {
                int idx = i;
                while (idx < s.length() && Character.isLetter(s.charAt(idx))) {
                    idx++;
                }
                if (!numq.isEmpty()) {
                    String str = s.substring(i, idx);
                    while (strq.size() >= numq.size()) {
                        str = strq.pop() + str;
                    }
                    strq.push(str);
                } else {
                    builder.append(s.substring(i, idx));
                }
                i = idx;
            } else if (s.charAt(i) == ']') {
                String str  = strq.pop();
                int cnt = numq.pop();
                while (strq.size() > numq.size()) {
                    str = strq.pop() + str;
                }
                StringBuilder temp = new StringBuilder();
                while (cnt-- >0) {
                    temp.append(str);
                }
                if (numq.isEmpty()) {
                    builder.append(temp.toString());
                } else {
                    strq.push(temp.toString());
                }
                i++;
            }else {
                //s.charAt(i) == '[' 不用管，直接丢掉
                i++;
            }
        }
        return builder.toString();
    }

//    abcabccdcdcdef
//    abcabccdcdcdef
//    "3[z]2[2[y]pq4[2[jk]e1[f]]]ef"
    public static void main(String[] args) {
        String s = "3[z]2[2[y]pq4[2[jk]e1[f]]]ef";
        String[] split = s.split("]");

        Lc394 lc394 = new Lc394();
        System.out.println(lc394.decodeString(s));
    }


}
